package com.share.rule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.api.rule.domain.*;

import com.share.rule.mapper.FeeRuleMapper;
import com.share.rule.service.IFeeRuleService;
import lombok.extern.slf4j.Slf4j;
import org.drools.kiesession.rulebase.InternalKnowledgeBase;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class FeeRuleServiceImpl extends ServiceImpl<FeeRuleMapper, FeeRule> implements IFeeRuleService {

    @Autowired
    private FeeRuleMapper feeRuleMapper;

    @Autowired
    private KieContainer kieContainer;

    /**
     * 查询费用规则列表
     * @param feeRule 规则对象
     * @return 规则列表
     */
    @Override
    public List<FeeRule> selectFeeRuleList(FeeRule feeRule) {
        return feeRuleMapper.selectFeeRuleList(feeRule);
    }


    /**
     * 获取全部费用规则
     * @return 全部费用规则
     */
    @Override
    public List<FeeRule> getALLFeeRuleList() {
        return feeRuleMapper.selectList(new LambdaQueryWrapper<FeeRule>().eq(FeeRule::getStatus, "1"));
    }

    /**
     * 计费规则
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        //封装传入对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDurations(feeRuleRequestForm.getDuration());
        log.info("传入参数：{}", JSON.toJSONString(feeRuleRequest));

        // 开启会话
        KieSession kieSession = kieContainer.newKieSession();

        //封装返回对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse", feeRuleResponse);
        // 设置订单对象
        kieSession.insert(feeRuleRequest);
        // 触发规则
        kieSession.fireAllRules();
        // 中止会话
        kieSession.dispose();
        log.info("计算结果：{}", JSON.toJSONString(feeRuleResponse));

        //封装返回对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        feeRuleResponseVo.setTotalAmount(BigDecimal.valueOf(feeRuleResponse.getTotalAmount()));
        feeRuleResponseVo.setExceedPrice(BigDecimal.valueOf(feeRuleResponse.getExceedPrice()));
        feeRuleResponseVo.setExceedDescription(feeRuleResponse.getExceedDescription());
        feeRuleResponseVo.setExceedPrice(BigDecimal.valueOf(feeRuleResponse.getExceedPrice()));
        feeRuleResponseVo.setFreeDescription(feeRuleResponse.getFreeDescription());
        return feeRuleResponseVo;
    }
}
